package com.sparrow.filter;

import com.sparrow.manage.monitor.AccessMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class PortalPageViewFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(PortalPageViewFilter.class);

    private String[] unStatisticPages;

    public void setUnStatisticPages(String[] unStatisticPages) {
        this.unStatisticPages = unStatisticPages;
    }

    @Override
    public void init(FilterConfig filterConfig) {
        logger.info("portal page view monitor init...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        boolean isMonitor = true;
        if(unStatisticPages != null){
            String servletPath = request.getServletPath();
            for (String unstatistic : unStatisticPages){
                if(servletPath.startsWith(unstatistic)){
                    isMonitor = false;
                    break;
                }
            }
        }

        if(isMonitor){
            AccessMonitor.AccessMonitorHolder.INSTANCE.access(request.getRemoteAddr());
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        logger.info("portal page view monitor destroy...");
    }
}
